package com.jzlin.funhub.admin.service.question;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jzlin.funhub.admin.model.dto.QuestionPageDTO;
import com.jzlin.funhub.admin.model.req.QuestionPageReq;
import com.jzlin.funhub.admin.model.entity.Question;
import com.jzlin.funhub.admin.mapper.QuestionMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jzlin.funhub.admin.model.req.QuestionPublishReq;
import com.jzlin.funhub.admin.model.req.QuestionSaveDraftReq;
import com.jzlin.funhub.admin.model.resp.QuestionDetailResp;
import com.jzlin.funhub.framework.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 问题记录表 服务实现类
 * </p>
 *
 * @author jzlin
 * @since 2025-05-14
 */
@Service
public class QuestionService extends ServiceImpl<QuestionMapper, Question> {

    @Autowired
    private RedisUtil redisUtil;

    /**
     * 分页查询列表
     * @param req 查询条件
     * @return
     */
    public IPage<QuestionPageDTO> queryPage(QuestionPageReq req){
        IPage<?> pageParam = new Page<>(req.getCurrent(), req.getSize());

        return this.baseMapper.queryPage(pageParam, req);
    }

    /**
     * 查询问题详情
     * @param questionId 问题id
     * @return
     */
    public QuestionDetailResp getDetail(Long questionId){
        Question question = this.getById(questionId);
        return new QuestionDetailResp(question);
    }

    /**
     * 保存问题草稿
     * @param req
     */
    public Long saveDraft(QuestionSaveDraftReq req) {
        Question question = new Question();
        question.setTitle(req.getTitle());
        question.setSummary(req.getSummary());
        question.setContent(req.getContent());
        question.setIsDraft(Boolean.TRUE);
        question.setCategoryId(req.getCategoryId());

        this.save(question);
        return question.getId();
    }

    /**
     * 发布问题
     * @param req
     */
    public Long publishNewQuestion(QuestionPublishReq req) {
        Question question = new Question();
        question.setTitle(req.getTitle());
        question.setSummary(req.getSummary());
        question.setContent(req.getContent());
        question.setIsDraft(Boolean.FALSE);
        question.setCategoryId(req.getCategoryId());

        this.save(question);
        return question.getId();
    }

    /**
     * 回答数+1
     */
    public void increaseAnswerCount(Long questionId) {
        UpdateWrapper<Question> updateWrapper = new UpdateWrapper<>();
        updateWrapper.setIncrBy("answer_count", 1);
        updateWrapper.eq("id", questionId);

        this.update(updateWrapper);
    }
}
